/**
  ******************************************************************************
  * @file TIM/PWM_Output/main.c 
  * @author  MCD Application Team
  * @version  V3.0.0
  * @date  04/06/2009
  * @brief  Main program body
  ******************************************************************************
  * @copy
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2009 STMicroelectronics</center></h2>
  */ 

/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define audio_io          GPIOA
#define audio_stdby_pin   GPIO_Pin_2
#define audio_pwm         GPIO_Pin_3
#define potentiometer_in  GPIO_Pin_1
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
TIM_OCInitTypeDef  TIM_OCInitStructure;
ErrorStatus HSEStartUpStatus;
/* Private function prototypes -----------------------------------------------*/
void RCC_Configuration(void);
void GPIO_Configuration(void);
void audio_pwm_configuration(void);
void timer_configuration(void);
void NVIC_Configuration(void);
void potentiometer_Configuration(void);
/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Main program
  * @param  None
  * @retval : None
  */
int main(void)
{
  RCC_Configuration();
  
  NVIC_Configuration();
  
  GPIO_Configuration();
  
  GPIO_ResetBits(audio_io, audio_stdby_pin);      /* enable TS4871 output */
  
  potentiometer_Configuration();
  
  audio_pwm_configuration(); 
  
  timer_configuration();   
  
  while(1);;
}

/**
  * @brief  Configures the different system clocks.
  * @param  None
  * @retval : None
  */
void RCC_Configuration(void)
{
  /* RCC system reset(for debug purpose) */
  RCC_DeInit();

  /* Enable HSE */
  RCC_HSEConfig(RCC_HSE_ON);

  /* Wait till HSE is ready */
  HSEStartUpStatus = RCC_WaitForHSEStartUp();

  if (HSEStartUpStatus == SUCCESS)
  {
    /* Enable Prefetch Buffer */
    FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);

    /* Flash 2 wait state */
    FLASH_SetLatency(FLASH_Latency_2);

    /* HCLK = SYSCLK */
    RCC_HCLKConfig(RCC_SYSCLK_Div1);

    /* PCLK2 = HCLK */
    RCC_PCLK2Config(RCC_HCLK_Div1);

    /* PCLK1 = HCLK/4 */
    RCC_PCLK1Config(RCC_HCLK_Div4);

    /* PLLCLK = 8MHz * 9 = 72 MHz */
    RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);

    /* Enable PLL */
    RCC_PLLCmd(ENABLE);

    /* Wait till PLL is ready */
    while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
    {}

    /* Select PLL as system clock source */
    RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);

    /* Wait till PLL is used as system clock source */
    while (RCC_GetSYSCLKSource() != 0x08)
    {}
  }

  /* TIM2 & TIM3 clock enable */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 | RCC_APB1Periph_TIM3, ENABLE);

  /* GPIOA & ADC1 clock enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_ADC1, ENABLE);
}

void NVIC_Configuration(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;

  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
 
  NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
}


/**
  * @brief  Configure the TIM3 Ouput Channels.
  * @param  None
  * @retval : None
  */
void GPIO_Configuration(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /*GPIOA Configuration: PA.3 => audio pwm output(AF_PP)  */
  GPIO_InitStructure.GPIO_Pin =  audio_pwm;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  GPIO_Init(audio_io, &GPIO_InitStructure);

  /*GPIOA Configuration: PA.2 => audio standby (open drain) */
  GPIO_InitStructure.GPIO_Pin =  audio_stdby_pin;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  GPIO_Init(audio_io, &GPIO_InitStructure);
  
  /*GPIOA Configuration: PA.1 => Potentiometer intput(analog input) */
  GPIO_InitStructure.GPIO_Pin = potentiometer_in;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;  
  GPIO_Init(GPIOA, &GPIO_InitStructure);
}

/**
  * @brief  Configure the TIM2 to output the PWM signal to drive the TS4871
  * @param  None
  * @retval : None
  */
void audio_pwm_configuration(void)
{
  u16 temp;  
  /* -----------------------------------------------------------------------
    TIM2 Configuration: 
    TIM2CLK = 36 MHz, Prescaler = 11, TIM2 counter clock = 3 MHz
    TIM2 ARR Register = 7499 => TIM2 Frequency = TIM2 counter clock/(ARR + 1)
    TIM2 Frequency = 400Hz. (min)
    TIM2 Channel4 duty cycle = (TIM2_CCR4/ TIM2_ARR) * 100 = 50%
    TIM2 ARR Register = 2999 => TIM2 Frequency = TIM2 counter clock/(ARR + 1)
    TIM2 Frequency = 1KHz. (max)
  ----------------------------------------------------------------------- */
  TIM_DeInit(TIM2);
  
  ADC_Cmd(ADC1, ENABLE);    /* start ADC convert */ 
  while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET); /* waiting for the end of the convert */   
  ADC_ClearFlag(ADC1, ADC_FLAG_EOC);  /* clear the flag of EOC */
  temp = ADC_GetConversionValue(ADC1);    /* get the value of the ADC */
  temp = (temp * (7499 - 2999)) / 0xFFF  + 2999; /* calculate the ARR value according to the value of the ADC */
 
  TIM_TimeBaseStructure.TIM_Period = temp;   /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 11;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;  /* PWM1 Mode configuration: Channel4 */ 
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = temp / 2;
  TIM_OC4Init(TIM2, &TIM_OCInitStructure);
  TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable);
  TIM_ARRPreloadConfig(TIM2, ENABLE);

  TIM_Cmd(TIM2, ENABLE);   /* TIM2 enable counter */
}


/**
  * @brief  Configure the TIM3 to generate the interrupt every 5ms
  * @param  None
  * @retval : None
  */
void timer_configuration(void)
{
  /* ---------------------------------------------------------------
    TIM3 Configuration: Timing Mode:
    TIM3CLK = 36 MHz, Prescaler = 11, TIM3 counter clock = 3MHz
    TIM3 ARR Register = 14999=> TIM3 Frequency = TIM3 counter clock/(ARR + 1)
    TIM3 Frequency = 200Hz (5ms).
  --------------------------------------------------------------- */

  TIM_DeInit(TIM3);         /* deinitiate */
  
  TIM_TimeBaseStructure.TIM_Period = 14999;   /* Time base configuration */
  TIM_TimeBaseStructure.TIM_Prescaler = 11;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;   /* Timing Mode :Channel1 */
  TIM_OC1Init(TIM3, &TIM_OCInitStructure);
  TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
  TIM_ARRPreloadConfig(TIM3, ENABLE);  

  TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);   /* TIM IT enable */

  TIM_Cmd(TIM3, ENABLE);  /* TIM3 enable counter */
}

/**
  * @brief  Configure the ADC1 channel1 to get the value of the potentiometer
  * @param  None
  * @retval : None
  */
void potentiometer_Configuration(void)
{
  ADC_InitTypeDef ADC_InitStructure;
  
  ADC_DeInit(ADC1);   
  
  /* ADC1 configuration ------------------------------------------------------*/
  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;    /* independent mode */
  ADC_InitStructure.ADC_ScanConvMode = DISABLE;         /* disable scan mode */
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;   /* disable continuous mode */
  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; /* no external trigger */
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;  /* right align */
  ADC_InitStructure.ADC_NbrOfChannel = 1;
  ADC_Init(ADC1, &ADC_InitStructure);

  /* ADC1 regular channel1 configuration */ 
  ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5);

  /* Enable ADC1 */
  ADC_Cmd(ADC1, ENABLE);

  /* Enable ADC1 reset calibaration register */   
  ADC_ResetCalibration(ADC1);

  /* Check the end of ADC1 reset calibration register */
  while(ADC_GetResetCalibrationStatus(ADC1));

  /* Start ADC1 calibaration */
  ADC_StartCalibration(ADC1);
  
  /* Check the end of ADC1 calibration */
  while(ADC_GetCalibrationStatus(ADC1));
}


#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval : None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  while (1)
  {}
}
#endif

/**
  * @}
  */ 

/**
  * @}
  */ 

/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
